﻿using NHibernate;
using NHibernate.Cfg;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace Mengsk.ProxyDelivery.Dao.HibernateImpl
{
    public class NHibernateHelper
    {
        public const string DB_MSSQL = "SQL Server";

        public const string DB_MYSQL = "My SQL";

        private static readonly DateTime msMinDateTime = new DateTime(1970, 1, 1);
        private static readonly DateTime myMinDateTime = new DateTime(1000, 1, 1);
        private static DateTime minDateTime = msMinDateTime;

        private static ISessionFactory sessionFactory = null;

        private static string dbType = null;

        public static string DataType
        {
            get { return dbType; }
            set
            {
                dbType = value;
                minDateTime = dbType == DB_MSSQL ? msMinDateTime : myMinDateTime;
                if (sessionFactory != null)
                {
                    sessionFactory.Close();
                }
                sessionFactory = null;
            }
        }

        public static DateTime GetDBMinTime()
        {
            return msMinDateTime;
        }

        public static ISession OpenSession()
        {
            if (sessionFactory == null)
            {
                string dir = new FileInfo(typeof(NHibernateHelper).Assembly.Location).DirectoryName;
                string file = DataType == DB_MSSQL ? "MsSql.cfg.xml" : "MySql.cfg.xml";
                Configuration cfg = new Configuration().Configure(dir + "\\Config\\MapFiles\\" + file);
                string[] files = Directory.GetFiles(dir + "\\Config\\MapFiles\\", "*.hbm.xml");
                foreach (var hbmFile in files)
                {
                    try
                    {
                        cfg.AddXmlFile(hbmFile);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
                sessionFactory = cfg.BuildSessionFactory();
            }
            var session = sessionFactory.OpenSession();
            return session;
        }
    }
}
